#!/bin/bash

function readProperty(){
    # 参数校验
    if [ ! -n "$1" ] || [ ! -f "$2" ]; then
        echo "Usage: ${FUNCNAME[0]} [key file]"
    else
        # 属性名称
        # x.z.y -> x\.z\.y 特殊字符转义，方便在后续的sed命令中使用
        key=`echo $1 | sed 's/\./\\\./g'`
        cat $2 | sed -n -e "s/^[ ]*//g;/^#/d;s/^$key\s*=\s*//p" | tail -1
    fi
}

function loadProperties(){
    # 参数校验
    if [ ! -f "$1" ]; then
        echo "Usage: ${FUNCNAME[0]} [file]"
    else
        echo >> $1
        v_tmp=`date "+%Y%m%d%H%M%S%s"`
        cat $1 | grep -v ^\\s*\\# | grep -v ^$ | sed 's/^\s*//g' | sed 's/\s*=\s*/=/g' > ${v_tmp}
        while read line
        do
            items=(${line//=/ })
            key=${items[0]}
            key=`echo ${key} | sed 's/\./\_/g'`
            value=${items[1]}
            echo "export  ${key}=${value}"
            export  ${key}=${value}
        done < ${v_tmp}
        rm -f ${v_tmp}
    fi
}

if [ "$1" == "read" ]; then
    key=`echo $2 | sed 's/\./\_/g'`
    export ${key}=`readProperty $2 $3`
elif [ "$1" == "load" ]; then
    loadProperties $2
else
    echo "Usage: $0 [read key file] | [load file]"
fi